package com.jwl.idc.http;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

/**
 * Created by liangfan on 2015/12/30.
 * descript:http连接接口
 */
public class HttpClientApi {

    public static final String UTF_8 = "UTF-8";
    public static final String CONTENT_TYPE = "application/octet-stream";
    private final static int TIMEOUT_CONNECTION = 30000;
    private final static int TIMEOUT_SOCKET = 30000;
    private final static int RETRY_TIME = 1;



    public static String _post(String url, Map<String, Object> params,
                               Map<String, File> files) throws AppException {
        HttpClient httpClient = null;
        PostMethod httpPost = null;
        int length = (params == null ? 0 : params.size())
                + (files == null ? 0 : files.size());
        Part[] parts = new Part[length];
        int i = 0;
        if (params != null)
            for (String name : params.keySet()) {

                parts[i++] = new StringPart(name, String.valueOf(params
                        .get(name)), UTF_8);
            }

        if (files != null)
            for (String file : files.keySet()) {
                try {
                    File mfile = files.get(file);
                    String path = mfile.getPath();
                    if (path.endsWith(".png")) {
                        parts[i++] = new FilePart(file, files.get(file),
                                "image/png", "ISO-8859-1");
                    } else if (path.endsWith(".jpg")) {
                        parts[i++] = new FilePart(file, files.get(file),
                                "image/jpeg", "ISO-8859-1");
                    } else if(path.endsWith(".txt")) {
                        parts[i++] = new FilePart(file, files.get(file),
                                CONTENT_TYPE, UTF_8);
                    }
                    // parts[i++] = new FilePart(file, files.get(file),
                    // CONTENT_TYPE, UTF_8
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

        httpClient = getHttpClient();
        httpPost = getHttpPost(url);
        httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost
                .getParams()));
        String responseBody = "";

        int time = 0;
        do {
            try {
                int statusCode = httpClient.executeMethod(httpPost);
                if (statusCode == HttpStatus.SC_OK) {
                    responseBody = httpPost.getResponseBodyAsString();
                    return responseBody;
                } else {
                    throw AppException.http(statusCode);
                }
            } catch (HttpException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                e.printStackTrace();
            } catch (IOException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                e.printStackTrace();
                throw AppException.network(e);
            }

        } while (time < RETRY_TIME);
        return "";
    }

    private static HttpClient getHttpClient() {
        HttpClient httpClient = new HttpClient();
        // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
        httpClient.getParams().setCookiePolicy(
                CookiePolicy.BROWSER_COMPATIBILITY);
        // 设置 默认的超时重试处理策略
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());
        // 设置 连接超时时间
        httpClient.getHttpConnectionManager().getParams()
                .setConnectionTimeout(TIMEOUT_CONNECTION);
        // 设置 读数据超时时间
        httpClient.getHttpConnectionManager().getParams()
                .setSoTimeout(TIMEOUT_SOCKET);
        // 设置 字符集
        httpClient.getParams().setContentCharset(UTF_8);
        return httpClient;
    }

    private static PostMethod getHttpPost(String url) {
        PostMethod httpPost = new PostMethod(url);
        // 设置 请求超时时间
        httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
        // httpPost.setRequestHeader("Host", "www.oschina.net");
        httpPost.setRequestHeader("Connection", "Keep-Alive");
        // httpPost.setRequestHeader("Cookie", cookie);
        // httpPost.setRequestHeader("User-Agent", userAgent);
        return httpPost;
    }

    private static GetMethod getHttpGet(String url, String cookie,
                                        String userAgent) {
        GetMethod httpGet = new GetMethod(url);
        // 设置 请求超时时间
        httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET);
        httpGet.setRequestHeader("Host", URLs.HOST);
        httpGet.setRequestHeader("Connection", "Keep-Alive");
        httpGet.setRequestHeader("Cookie", cookie);
        httpGet.setRequestHeader("User-Agent", userAgent);
        return httpGet;
    }
}
